# 留言板的表单

from django import forms
from django.core import validators

from front.models import User, Article


class MessageBoardForm(forms.Form):
    title = forms.CharField(min_length=2, max_length=20, label='标题',
                            error_messages={
                                "min_length": '标题最小长度不能小于2！',
                                "max_length": '标题最大长度不能超过20！',
                            })
    content = forms.CharField(widget=forms.Textarea, label='内容')
    email = forms.EmailField(label='邮箱')


class RegisterForm(forms.Form):
    username = forms.CharField(min_length=2, max_length=20, label='用户名', error_messages={
        "min_length": '标题最小长度不能小于2！',
        "max_length": '标题最大长度不能超过20！',
    })
    password = forms.CharField(widget=forms.PasswordInput, label='密码', min_length=2, max_length=20, error_messages={
        "min_length": '标题最小长度不能小于2！',
        "max_length": '标题最大长度不能超过20！',
    })

    password1 = forms.CharField(widget=forms.PasswordInput, label='确认密码', min_length=2, max_length=20, error_messages={
        "min_length": '标题最小长度不能小于2！',
        "max_length": '标题最大长度不能超过20！',
    })
    tel = forms.CharField(validators=[validators.RegexValidator(r'^1[3-9]\d{9}', message='手机号码格式不符合')])

    # 自定义验证(验证顺序，先验证Form表单的，再验证下面的)
    # 单个字段验证
    # clean_字段名
    def clean_tel(self):
        tel = self.cleaned_data.get('tel')
        # 从数据库中查找tel
        if User.objects.filter(tel=tel).exists():
            raise forms.ValidationError('手机号码已经存在')
        return tel

    # 多个字段验证
    def clean(self):
        # 这里需要调用父类的方法
        clean_super = super().clean()
        # tel = clean_super.get('tel')
        # # 从数据库中查找tel
        # if User.objects.filter(tel=tel).exists():
        #     raise forms.ValidationError('手机号码已经存在')

        password = clean_super.get('password')
        password1 = clean_super.get('password1')
        if password != password1:
            raise forms.ValidationError('两个密码不一致')


class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        # fields = ['title', 'content']
        fields = "__all__"
        # exclude = ['category']
        error_messages = {
            'category':{
                'required':'category不能为空'
            }
        }
